package com.tg.app.activity.device.settings;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.util.Consumer;

import com.appbase.custom.app.AppStatusChangeListener;
import com.appbase.custom.app.STATUS;
import com.tange.base.toolkit.DimenUtil;
import com.tange.base.toolkit.NetworkUtil;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.core.device.facade.ConnectStatus;
import com.tange.core.device.facade.DeviceFacade;
import com.tange.core.device.facade.Instruction;
import com.tange.core.device.facade.Status;
import com.tg.app.R;
import com.tg.app.TGDevice;
import com.tg.app.activity.base.DeviceSettingsBaseActivity;
import com.tg.app.activity.device.DeviceSettingsActivity;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.helper.AppHelper;
import com.tg.appcommon.android.DialogUtil;
import com.tg.appcommon.android.OnUiThreadDelayedStatusHelper;
import com.tg.appcommon.android.Packet;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.app.AppStatusObserver;
import com.tg.data.bean.DeviceSettingsInfo;

public class SDCardStateActivity extends DeviceSettingsBaseActivity{
    private static final String TAG = "SDCardStateActivity-log";
    private DeviceSettingsInfo info;
    private DeviceFacade deviceFacade;
    private View formatView;
    private PopupWindow pop;
    private boolean isSendCmd = false;

    private TextView mSDCardStatus;


    private final OnUiThreadDelayedStatusHelper mDeviceInfoHelper = new OnUiThreadDelayedStatusHelper();
    private int mStartCount = 0;
    private boolean mIsFormating = false;
    private boolean mIsBackGround = false;
    private boolean mMustRequstStatus = false;

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mStartCount++;
        if (deviceFacade == null) return;
        TGLog.d(TAG, "startCount = " + mStartCount + ",camera.isNotConnected()" + deviceFacade.connected());
        if (mStartCount > 1 && mIsFormating){
            if (deviceFacade.connected() && NetworkUtil.isNetworkConnected(TGApplicationBase.getApplication())){
                deviceFacade.connect();
            }
        }
    }

    @Override
    protected void onSetupFailed() {
        mHandler.removeCallbacks(timeRunable);
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
        }
    }

    private void registerICameraListener(){
        if (deviceFacade != null) {
            deviceFacade.observeConnectStatus(connectStatusConsumer);
            deviceFacade.getInstruct().observeOnReceive(instructionConsumer);
        }
    }

    private void unregisterICameraListener() {
        if (deviceFacade != null) {
            deviceFacade.unObserveConnectStatus(connectStatusConsumer);
            deviceFacade.getInstruct().unObserveOnReceive(instructionConsumer);
        }
    }
        @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_sdcard_state_s);
        hideActionBar();
        info = getIntent().getParcelableExtra(DeviceSettingsActivity.EXT_DEVICE_INFO);
        deviceFacade = new DeviceFacade(info.uuid);
        initView();
        backClickEvent();
        AppStatusObserver.getInstance().registerListener(mAppStatusChangeListener);
        if (!NetworkUtil.isNetworkConnected(TGApplicationBase.getApplication())){
            TGToast.showToast(R.string.txt_network_anomaly);
        }

    }

    public void initView() {
        modifyToolBar(R.string.sdcard_state);
        mSDCardStatus = findViewById(R.id.text_sdcard_status);
        formatView = findViewById(R.id.formatbt);
        formatView.setOnClickListener(view -> {
            if (!TGDevice.getInstance().isNetwork(deviceFacade)){
                TGToast.showToast(R.string.txt_network_anomaly);
            }else{
                DialogUtil.openDlalog(SDCardStateActivity.this, R.string.sdcard_format_confirm, R.string.sdcard_empty_contents, R.string.confirm, R.string.dialog_cancel, v -> formatSDCard(), null);
            }
        });
        registerICameraListener();
        updateUI(true);
    }

    private void updateUI(boolean isFromCreate) {
        if (deviceFacade !=null&&!deviceFacade.connected() && isFromCreate){
            deviceFacade.connect();
            return;
        }

        if (info == null) {
            return;
        }

        if (info.total == 0) {  //没有sd卡
            mSDCardStatus.setText(R.string.text_nosdcard);
            formatView.setVisibility(View.GONE);
        } else if (info.total == -1) { //卡异常
            mSDCardStatus.setText(R.string.settings_sdcard_error);
            if (mIsFormating &&  !mIsBackGround){
                mIsFormating = false;
                showFailTip(R.string.format_failed);
            }
            formatView.setVisibility(View.GONE);

        } else if (info.total == -2){ //只读
            mSDCardStatus.setText(R.string.normal);
            if (mIsFormating &&  !mIsBackGround){
                mIsFormating = false;
                showFailTip(R.string.format_failed);
            }
        }else if (info.total == -3) {  //格式化中
            TGLog.d(TAG, "格式化中");
        } else { //卡正常
            mSDCardStatus.setText(R.string.normal);
            TGLog.d(TAG, "mIsFormating" + mIsFormating);
            if (mIsFormating &&  !mIsBackGround){
                mIsFormating = false;
                showToast(R.string.format_success);
            }
        }
    }


    @Override
    protected void onTimeFinish() {
        if (deviceFacade != null){
            TGLog.d(TAG, "onTimeFinish camera.isConnected：" + deviceFacade.connected());
            if (deviceFacade.connected()){
                mIsFormating = false;
                showFailTip(R.string.format_failed);
            }else{
                deviceFacade.connect();
            }
        }
    }

    private void showFailTip(final int resId){
        showToast(resId);
        onSetupFailed();
    }


    private void formatSDCard() {
        if (deviceFacade != null) {
            mIsFormating = true;
            showLoadingDialog(R.string.formating);
            mIsSetSuccess = false;
            mHandler.postDelayed(timeRunable, 180000);//格式化一张128G的内存卡需要一分三十秒
            AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_FORMATEXTSTORAGE_REQ, AVIOCTRLDEFs.SMsgAVIoctrlFormatExtStorageReq.parseContent(0));
        }
    }


    private final Consumer<ConnectStatus> connectStatusConsumer = new Consumer<ConnectStatus>() {
        @Override
        public void accept(ConnectStatus connectStatus) {
            Status status = connectStatus.getStatus();
            TGLog.d(TAG, "state = " + status);
            if (status == Status.SUCCESS) {
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_REQ, AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoReq.parseContent());
                mDeviceInfoHelper.executeOnUiThreadDelayed(() -> {
                    if (!mIsFormating){
                        showErrorData();
                    }else{
                        mIsFormating = false;
                        if (!mIsBackGround){
                            showFailTip(R.string.format_failed);
                        }
                    }
                }, 5000);
            }else if (status == Status.FAILED){
                TGThreadPool.executeOnUiThreadDelayed(() -> {
                    if (!TGApplicationBase.isBackGround()){
                        showErrorData();
                    }else{

                        onSetupFailed();
                    }
                }, 500);
            }
        }
    };


    private void showErrorData() {
        showFailTip(R.string.data_error);
        mSDCardStatus.setText(R.string.get_failed);
        formatView.setVisibility(View.GONE);
        if (mIsFormating && !mIsBackGround){
            mIsFormating = false;
            showFailTip(R.string.format_failed);
        }
    }

    private final Consumer<Instruction> instructionConsumer = new Consumer<Instruction>() {
        @Override
        public void accept(Instruction instruction) {
            if (instruction == null) {
                return;
            }
            final int type = instruction.getId();
            final byte[] data = instruction.getData();
            runOnUiThread(() -> {
                TGLog.d(TAG, "type = " + type);
                if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_FORMATEXTSTORAGE_RESP) {
                    byte result = data[4];
                    TGLog.d(TAG, "result = " + result);
                    if (result == 0) {
                        isSendCmd = true;
                        //格式化成功
                        mDeviceInfoHelper.init();
                        AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_REQ, AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoReq.parseContent());
                        completeSend();
                    } else {
                        if (!mIsBackGround){
                            mIsFormating = false;
                            showFailTip(R.string.format_failed);
                        }else{
                            mMustRequstStatus = true;
                        }
                    }
                } else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_RESP) {
                    TGLog.d(TAG, "mDeviceInfoHelper.isFaild() = " + mDeviceInfoHelper.isFaild());
                    if (!mDeviceInfoHelper.isFaild()){
                        mDeviceInfoHelper.setSuccess();
                        final int mTotalSize = Packet.byteArrayToInt_Little(data, 40);
                        final int free = Packet.byteArrayToInt_Little(data, 44);
                        onSetupFailed();

                        if (isSendCmd) {
                            if (!mIsBackGround){
                                mIsFormating = false;
                                showToast(R.string.format_success);
                            }else{
                                mMustRequstStatus = true;
                            }
                        }
                        info.free = free;
                        info.total = mTotalSize;
                        isSendCmd = false;
                        updateUI(false);
                        sendUpdateSettingBroadcast(info);
                    }
                }

            });

        }
    };

    private void showLoadingDialog(int resId) {
        if (isFinishing())return;
        setEnabled(false);
        @SuppressLint("InflateParams") View content = LayoutInflater.from(this).inflate(R.layout.pop_loading, null);
        pop = new PopupWindow(content, DimenUtil.dp2px(SDCardStateActivity.this, 225), DimenUtil.dp2px(SDCardStateActivity.this, 170), false);
        // 设置按钮的点击事件
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.7f;
        getWindow().setAttributes(params);
        ImageView iv = content.findViewById(R.id.doorbell_loading);
        TextView tv = content.findViewById(R.id.load_tip);
        tv.setText(getString(resId));
        AnimationDrawable account_edit = (AnimationDrawable) iv.getDrawable();
        account_edit.start();
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
        }
        View parent = getWindow().getDecorView();
        pop.showAtLocation(parent, Gravity.CENTER, 0, 0);
        pop.setOnDismissListener(() -> {
            WindowManager.LayoutParams params1 = getWindow().getAttributes();
            params1.alpha = 1f;
            getWindow().setAttributes(params1);
            setEnabled(true);
        });
    }

    private void setEnabled(boolean enabled){
        formatView.setClickable(enabled);
        findViewById(R.id.back_toolbar).setClickable(enabled);
    }

    private final AppStatusChangeListener mAppStatusChangeListener = new AppStatusChangeListener() {
        @Override
        public void onStatusChange(Activity currentActivity, int activityNumber, int status) {
            TGLog.d(TAG,"status = " + status + ", activityNumber" + activityNumber);
            if (activityNumber == 0 && status == STATUS.STATUS_BACKGROUND) { //后台
                mIsBackGround = true;
            } else if (status == STATUS.STATUS_FOREGROUND && currentActivity instanceof SDCardStateActivity) {
                mIsBackGround = false;
                TGLog.d(TAG,"mMustRequstStatus = " + mMustRequstStatus + ", activityNumber" + activityNumber);
                if (mMustRequstStatus && TGDevice.getInstance().isNetwork(deviceFacade)){
                    mMustRequstStatus = false;
                    mDeviceInfoHelper.init();
                    AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_REQ, AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoReq.parseContent());
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        AppStatusObserver.getInstance().unregisterListener(mAppStatusChangeListener);
        unregisterICameraListener();
        super.onDestroy();
    }

}
